package com.example.literj.kt.internal.schedulers

import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicLong

class RxThreadFactory(
    private val prefix: String,
    private val priority: Int,
    private val nonBlocking: Boolean
) : AtomicLong(), ThreadFactory {
    constructor(cPrefix: String) : this(cPrefix, Thread.NORM_PRIORITY)
    constructor(cPrefix: String, cPriority: Int) : this(cPrefix, cPriority, false)

    override fun toByte() = get().toByte()
    override fun toChar() = get().toChar()
    override fun toShort() = get().toShort()

    override fun newThread(r: Runnable?): Thread {
        val nameBuilder = StringBuilder(prefix).append('-').append(incrementAndGet())
        val name = nameBuilder.toString()
        val t =
            if (nonBlocking) RxCustomThread(r, name) else Thread(r, name)
        t.priority = priority
        t.isDaemon = true
        return t
    }

    internal class RxCustomThread(run: Runnable?, name: String) : Thread(run, name),
        NonBlockingThread
}